'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {

  async getRoot() {
    this.ctx.body = 'hi, egg';
    this.ctx.status = 200;
  }

  async login() {
    const result = await this.ctx.curl('106.15.191.76/user/login', {
      method: 'POST',
      contentType: 'json',
      data: {
        email: this.ctx.request.body.email,
        password: this.ctx.request.body.password,
      },
      dataType: 'json',
    });

    if (result.status === 200) {
      this.ctx.status = 200;
      this.ctx.body = result.data;
      this.ctx.session.user_id = result.data.id;
      this.ctx.session.email = result.data.email;
    } else if (result.status === 400) {
      this.ctx.status = 400;
      this.ctx.body = '登录失败，用户名或密码错误';
    }
  }

  async register() {
    const result = await this.ctx.curl('106.15.191.76/user/register', {
      method: 'POST',
      contentType: 'json',
      data: {
        email: this.ctx.request.body.email,
        password: this.ctx.request.body.password,
        name: this.ctx.request.body.name,
        position: this.ctx.request.body.position,
      },
      dataType: 'json',
    });

    this.ctx.status = result.status;
    if (result.status === 200) {
      this.ctx.body = '注册成功';
    } else if (result.status === 400 && result.data === 'duplicated email') {
      this.ctx.body = '邮箱已被注册';
    }
  }

  async getUser() {
    this.ctx.body = {
      user_id: this.ctx.session.user_id,
      email: this.ctx.session.email,
    };
    this.ctx.status = 200;
  }

  async logout() {
    this.ctx.session.user_id = null;
    this.ctx.session.email = null;
    this.ctx.status = 200;
  }
}

module.exports = HomeController;
